package com.ghc.service.impl;

import com.ghc.service.CodeValidateService;
import com.ghc.entity.AuthCode;
import com.ghc.repository.AuthCodeRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.data.domain.Example;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class CodeValidateServiceImpl implements CodeValidateService {

    private final AuthCodeRepository authCodeRepository;

    @Override
    public int validate(String email, String code) {
        AuthCode authCode = new AuthCode();
        authCode.setEmail(email);
        authCode.setCode(code);
        Example<AuthCode> example = Example.of(authCode);
        List<AuthCode> allAuthCodes = authCodeRepository.findAll(example);
        if (allAuthCodes.size() > 0){
            allAuthCodes.sort((a,b)->b.getExpiretime().compareTo(a.getExpiretime()));
            AuthCode authCode1 = allAuthCodes.get(0);
            boolean before = LocalDateTime.now().isBefore(authCode1.getExpiretime());
            if (before){
                return 0;
            }
            return 2;
        }
        return 1;
    }
}
